import { http } from '@/utils/http'


/**
 * *----------------------------图片上传-----------------------------------
 * @param {string or Ayyay} filePaths 图片本地路径
 * @returns {string or Ayyay} 图片网络地址
 * @example uploadApi('baseUrl')
 * @example uploadApi(['baseUrl-1','baseUrl-2'])
 */
export const uploadApi = async (filePaths: any) => {
    const urls = Array.isArray(filePaths) ? filePaths : [filePaths]

    if (!aliVal.host || Object.keys(aliVal).length === 0) {
        await _GET_ALIVAL()
    }
    const uploadPromises = urls.map(_UPLOAD_FILE)

    const results = await Promise.all(uploadPromises)

    return Array.isArray(filePaths) ? results : results[0]
}


var aliVal: any = {}

async function _GET_ALIVAL() {
    try {
        const res = await http<any>({
            url: 'https://weapp.miyingbl.com/api/common/oss_sign',
        })
        console.log('res', res)
        aliVal = res.data
    } catch (data) {
        console.log('data', data)
        aliVal = data
    }
}

let uploadTask = null;
function _UPLOAD_FILE(filePath: any) {
    return new Promise(async (resolve, reject) => {
        try {
            const date = Date.now()
            const { host, dir, policy, accessid, signature } = aliVal
            uploadTask=await uni.uploadFile({
                url: host, // oss 开发服务器地址
                filePath,
                name: 'file',
                formData: {
                    // oss 配置信息
                    key: `${dir}h-bl-app/${date}`,
                    policy,
                    OSSAccessKeyId: accessid,
                    signature,
                },
            })
            const networkUrl = `${host}/${dir}h-bl-app/${date}`
            console.log(networkUrl);

            return resolve(networkUrl)
        } catch (error) {
            reject(error)
        }
    })
}

// 停止上传视频
export const stopUpload = async() => {
  if (uploadTask !== null && typeof uploadTask === 'object') {
    // 取消上传任务
    uploadTask.abort();
    
    // 清空上传任务引用
    uploadTask = null;
  } else {
    console.error('没有正在进行的上传任务');
  }
}
